<?php
ini_set('display_errors',1); 
error_reporting(E_ALL);

## From form
$CN = 'test';
$givenName = 'dasanwwww';
$SN = 'Weerarathne';
##$mail = 'dasanwwww@dasangislab.lk';
##$Phone = $_POST['Phone'];
$pwdtxt = 'Text';

$AD_server = "192.168.1.76"; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "administrator@dasangislab.lk"; //Administrative user
$AD_Auth_PWD = "1qaz2wsx@"; //The password

$dn = 'CN='.$CN.',OU=dasan,DC=dasangislab,DC=lk';

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"";
$len = strlen($newPassword);
$newPassw = "";

for($i=0;$i<$len;$i++) {
    $newPassw .= "{$newPassword{$i}}\000";
}

## CONNNECT TO AD
$ds = ldap_connect($AD_server) or die('Fail to connect');
if ($ds) {
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // IMPORTANT
    $r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD) or die('Fail to authenticate'); //BIND

    $ldaprecord['cn'] = $CN;
    $ldaprecord['givenName'] = $givenName;
    $ldaprecord['sn'] = $SN;
    $ldaprecord['objectclass'][0] = "top";
    $ldaprecord['objectclass'][1] = "person";
    $ldaprecord['objectclass'][1] = "organizationalPerson";
    $ldaprecord['objectclass'][2] = "user";
    #$ldaprecord['mail'] = $mail;
    #$ldaprecord['telephoneNumber'] = $Phone;
    ##$ldaprecord["unicodepwd"] = $newPassw;
    $ldaprecord["sAMAccountName"] = $CN;
    $ldaprecord["UserAccountControl"] = "512";
//This is to prevent the user from beeing disabled. -->
http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

    $r = ldap_add($ds, $dn, $ldaprecord) or die('Fail to create');
   
} else {
    echo "cannot connect to LDAP server at $AD_server.";
}

?>